package com.ruanyun.modular.ry.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruanyun.base.pojo.page.LayuiPageFactory;
import com.ruanyun.base.consts.PublicCommon;
import com.ruanyun.base.pojo.page.LayuiPageInfo;
import com.ruanyun.modular.ry.api.vo.resp.AppVersionRespVo;
import com.ruanyun.modular.ry.entity.AppVersion;
import com.ruanyun.sys.core.shiro.ShiroKit;
import com.ruanyun.modular.ry.mapper.AppVersionMapper;
import com.ruanyun.modular.ry.model.params.AppVersionParam;
import com.ruanyun.modular.ry.model.result.AppVersionResult;
import com.ruanyun.modular.ry.service.AppVersionService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruanyun.sys.modular.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 版本号 服务实现类
 * </p>
 *
 * @author conan
 * @since 2021-01-08
 */
@Service
public class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersion> implements AppVersionService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseData add(AppVersionParam param) {
        AppVersion result = this.baseMapper.selectOne(Wrappers.<AppVersion>lambdaQuery().eq(AppVersion::getVersion, param.getVersion())
                .eq(AppVersion::getType, param.getType()
                ).ne(AppVersion::getDelFlag, PublicCommon.DEL_FLAG_DELETE));
        if (result != null) {
            return ResponseData.error("该版本已存在");
        }
        AppVersion entity = getEntity(param);
        Long sort = 0l;
        List<AppVersion> appVersionList = this.baseMapper.selectList(Wrappers.<AppVersion>lambdaQuery().eq(AppVersion::getDelFlag, PublicCommon.DEL_FLAG_NORMAL).orderByDesc(AppVersion::getSort));
        if (CollectionUtil.isNotEmpty(appVersionList)) {
            sort = appVersionList.get(0).getSort() + 1;
        }
        entity.setSort(sort);
        entity.setDelFlag(PublicCommon.DEL_FLAG_NORMAL);
        int insertCount = this.baseMapper.insert(entity);
        if (insertCount == 0) {
            return ResponseData.error("添加失败");
        }
        return ResponseData.success();
    }

    @Override
    public void delete(AppVersionParam param) {
        this.removeById(getKey(param));
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseData updateDelFlagById(Long id) {
        AppVersion entity = this.baseMapper.selectById(id);
        if (entity == null) {
            return ResponseData.error("该版本号不存在");
        }
        entity.setDelFlag(PublicCommon.DEL_FLAG_DELETE);
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("删除失败");
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData update(AppVersionParam param) {
        AppVersion appVersion = this.baseMapper.selectById(param.getId());
        if (appVersion == null) {
            return ResponseData.error("该版本号不存在");
        }
        AppVersion appVersionResult = this.baseMapper.selectOne(Wrappers.<AppVersion>lambdaQuery().
                eq(AppVersion::getVersion, param.getVersion())
                .eq(AppVersion::getType, appVersion.getType()).ne(AppVersion::getId, appVersion.getId())
                .ne(AppVersion::getDelFlag, PublicCommon.DEL_FLAG_DELETE));
        if (appVersionResult != null) {
            return ResponseData.error("该版本号已存在");
        }
        appVersion.setVersion(param.getVersion());
        appVersion.setFileName(param.getFileName());
        int updateCount = this.baseMapper.updateById(appVersion);
        if (updateCount == 0) {
            return ResponseData.error("修改失败");
        }
        return ResponseData.success();
    }

    @Override
    public AppVersionResult findBySpec(AppVersionParam param) {
        return null;
    }

    @Override
    public List<AppVersionResult> findListBySpec(AppVersionParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(AppVersionParam param) {
        Page pageContext = getPageContext();
        IPage<AppVersionResult> page = this.baseMapper.customPageList(pageContext, param);
        for (AppVersionResult record : page.getRecords()) {
            record.setCreateName(userMapper.selectById(record.getCreateBy()) == null ? null : userMapper.selectById(record.getCreateBy()).getName());
            record.setUpdateName(userMapper.selectById(record.getUpdateBy()) == null ? null : userMapper.selectById(record.getUpdateBy()).getName());
        }
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(AppVersionParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private AppVersion getOldEntity(AppVersionParam param) {
        return this.getById(getKey(param));
    }

    private AppVersion getEntity(AppVersionParam param) {
        AppVersion entity = new AppVersion();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 启用
     *
     * @param id
     * @return
     */
    @Override
    public ResponseData enableById(Long id) {
        AppVersion entity = this.baseMapper.selectById(id);
        if (entity == null) {
            return ResponseData.error("该版本号不存在");
        }
        entity.setDelFlag(PublicCommon.DEL_FLAG_NORMAL);
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("启用失败");
        }
        return ResponseData.success();
    }

    /**
     * 禁用
     *
     * @param id
     * @return
     */
    @Override
    public ResponseData disableById(Long id) {
        AppVersion entity = this.baseMapper.selectById(id);
        if (entity == null) {
            return ResponseData.error("该版本号不存在");
        }
        entity.setDelFlag(PublicCommon.DEL_FLAG_DISABLE);
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("禁用失败");
        }
        return ResponseData.success();
    }

    /**
     * 通过软件版本号返回是否需要更新系统
     *
     * @return
     */
    @Override
    public ResponseData isUpgrade() {
        AppVersion resultAppVersion = this.baseMapper.selectOne(Wrappers.<AppVersion>lambdaQuery().eq(AppVersion::getDelFlag, PublicCommon.DEL_FLAG_NORMAL).orderByDesc(AppVersion::getVersion).last(" limit 1"));
        if (resultAppVersion == null) {
            return ResponseData.error("版本号不存在");
        }
        AppVersionRespVo appVersionRespVo = new AppVersionRespVo();
        appVersionRespVo.setVersion(resultAppVersion.getVersion());
        appVersionRespVo.setApk(resultAppVersion.getApk());
        return ResponseData.success(appVersionRespVo);
    }
}
